package com.younion.action.consumer.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.younion.action.consumer.AbstractRequestConsumer;
import com.younion.action.interactive.mobile.ApiConstant;
import com.younion.action.interactive.mobile.ResultObject;
import com.younion.business.ICardCountInitService;
import com.younion.business.ICardEntityService;
import com.younion.business.IMemberCardCostCountService;
import com.younion.business.IMemberCardService;
import com.younion.business.IMembercardServiceService;
import com.younion.business.IRegisterUserService;
import com.younion.business.IServiceInitService;
import com.younion.common.constants.SysConstants;
import com.younion.model.ApplyCardResult;
import com.younion.util.HttpRequestUtils;
import com.younion.util.JsonUtils;
import com.younion.util.UUIDUtil;
import com.younion.util.config.ConfigHelper;
import com.younion.vo.API_CardEntityVO;
import com.younion.vo.CardCountInitVO;
import com.younion.vo.MemberCardCostCountVO;
import com.younion.vo.MemberCardVO;
import com.younion.vo.MembercardServiceVO;
import com.younion.vo.RegisterUserVO;
import com.younion.vo.ServiceInitVO;

public class ApplyCardConsumer extends AbstractRequestConsumer {
	private ICardEntityService cardEntityService = null;
	private IMemberCardService memberCardService = null;
	private IRegisterUserService registerUserService = null;
	private ICardCountInitService cardCountInitService = null;
	private IMemberCardCostCountService memberCardCostCountService = null;
	private IServiceInitService serviceInitService = null;
	private IMembercardServiceService membercardServiceService = null;

	public void setMembercardServiceService(
			IMembercardServiceService membercardServiceService) {
		this.membercardServiceService = membercardServiceService;
	}

	public void setServiceInitService(IServiceInitService serviceInitService) {
		this.serviceInitService = serviceInitService;
	}

	public void setMemberCardCostCountService(
			IMemberCardCostCountService memberCardCostCountService) {
		this.memberCardCostCountService = memberCardCostCountService;
	}

	public void setCardCountInitService(
			ICardCountInitService cardCountInitService) {
		this.cardCountInitService = cardCountInitService;
	}

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return applyCard(request, response);
	}

	public String applyCard(HttpServletRequest request,
			HttpServletResponse response) {
		String card_id = request.getParameter("card_id");
		String user_token = request.getParameter("user_token");
		String memberEmail = request.getParameter("email");
		String memberQq = request.getParameter("qq");
		String membeIdCard = request.getParameter("idcard");
		String memberBirth = request.getParameter("birthday");
		String memberName = request.getParameter("member_name");
		String memberSex = request.getParameter("member_sex");
		String memberPhone = request.getParameter("phone");
		String isAllowPush = request.getParameter("is_allow_push");
		ApplyCardResult applyCardResult = new ApplyCardResult();
		ResultObject resultObject = new ResultObject();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Map paramMap = new HashMap();
			paramMap.put("userToken", user_token);
			RegisterUserVO RegisterUserVO = registerUserService
					.getVOByMap(paramMap);
			if (RegisterUserVO != null) {
				Map getCountMap = new HashMap();
				getCountMap.put("userId", RegisterUserVO.getId());
				getCountMap.put("cardId", card_id);
				int count = memberCardService.getCountByMap(getCountMap);
				if (count < 1) {// 没有申请过
					Map api_paramMap = new HashMap();
					api_paramMap.put("id", card_id);
					API_CardEntityVO cardEntityVO = cardEntityService
							.selectApiCardEntityByMap(api_paramMap);
					if (cardEntityVO.getCustomerVO().getCooperationStaus() != null
							&& cardEntityVO.getCustomerVO()
									.getCooperationStaus() == 0) {
						resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
						resultObject.setMsg("该商家与优联尚未合作，请联系商家开通服务");
					} else {
						MemberCardVO memberCardVO = new MemberCardVO();
						UUIDUtil UUIDUtil = new UUIDUtil();
						memberCardVO.setCardId(cardEntityVO.getId());
						memberCardVO.setSchemeCode(UUIDUtil.getUuid()
								.toString());
						memberCardVO.setCardCode(cardEntityVO.getSchemeCode());
						memberCardVO.setUserId(RegisterUserVO.getId());
						memberCardVO.setMemberEmail(memberEmail);
						memberCardVO.setMemberQq(memberQq);
						memberCardVO.setMembeIdCard(membeIdCard);
						memberCardVO.setHasRecharged(0);
						memberCardVO.setCardBalance(0.0);
						memberCardVO.setScore(0);
						memberCardVO.setCustomerId(cardEntityVO.getCustomerVO().getId());
						try {
							Date birthday = sdf.parse(memberBirth);
							memberCardVO.setMemberBirth(birthday);
						} catch (Exception e) {

						}
						memberCardVO.setMemberName(memberName);
						try {
							memberCardVO.setMemberSex(new Integer(memberSex));
						} catch (Exception e) {

						}
						memberCardVO.setMemberPhone(memberPhone);
						try {
							memberCardVO
									.setIsAllowPush(new Integer(isAllowPush));
						} catch (Exception e) {

						}
						memberCardVO.setIsMobileUser(1);
						// 生成卡实例
						String img_url_pre = ConfigHelper.fastGetConfig(
								"interface", "img_url_pre",
								"http://localhost:8080/younonmember/");
						memberCardVO.setSendType(1);// 1：自主申请 0：商家自发
						//将实体卡有效期带入到实例
						memberCardVO.setExpiryDateFrom(cardEntityVO.getExpiryDateFrom());
						memberCardVO.setExpiryDateTo(cardEntityVO.getExpiryDateTo());
						int memberid = memberCardService.saveReturnKey(memberCardVO);
						applyCardResult.setCard_id(new Integer(memberid)
								.toString());
						applyCardResult
								.setCard_no(memberCardVO.getSchemeCode());
						applyCardResult.setTime_from(sdf.format(cardEntityVO
								.getExpiryDateFrom()));
						applyCardResult.setTime_to(sdf.format(cardEntityVO
								.getExpiryDateTo()));
						applyCardResult.setCluber_welfare(cardEntityVO
								.getWelfare());
						applyCardResult.setCard_num(cardEntityVO
								.getCardIssueAmount().toString());
						int limitAmount = cardEntityVO.getLimitAmount() == null ? 0
								: cardEntityVO.getLimitAmount();
						int issueAmount = cardEntityVO.getCardIssueAmount() == null ? 0
								: cardEntityVO.getCardIssueAmount();
						applyCardResult.setCard_surplus_num(new Integer(
								limitAmount - issueAmount).toString());
						applyCardResult.setNonactivatedPic(img_url_pre
								+ SysConstants.CARD_IMG_URL + "/"
								+ cardEntityVO.getId() + "/"
								+ cardEntityVO.getNonactivatedPic());
						applyCardResult.setActivatedPic(img_url_pre
								+ SysConstants.CARD_IMG_URL + "/"
								+ cardEntityVO.getId() + "/"
								+ cardEntityVO.getActivatedPic());
						applyCardResult.setCard_directions(cardEntityVO
								.getUseNotes());
						resultObject.setResult(applyCardResult);
						resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
						// 发卡成功后需要更新发卡数
						Map updateSendCardAmountParamMap = new HashMap();
						updateSendCardAmountParamMap.put("id", memberCardVO
								.getCardId());
						updateSendCardAmountParamMap.put("amount", 1);
						cardEntityService
								.updateSendCardAmountByMap(updateSendCardAmountParamMap);
						memberCardVO.setId(memberid);
						// 如果是发卡那么就需要将实体卡的初始值带入实例
						Map cardCountInitServiceParamMap = new HashMap();
						//paramMap.put("cardEntityId", memberCardVO.getCardId());
						//paramMap.put("cardEntity", cardEntityVO);
						List<CardCountInitVO> cardCountInitList = (List<CardCountInitVO>) cardCountInitService
								.getByMap(cardCountInitServiceParamMap);
						if (cardCountInitList != null
								&& cardCountInitList.size() > 0) {
							List<MemberCardCostCountVO> memberCardCostCountVOList = new ArrayList<MemberCardCostCountVO>();
							for (CardCountInitVO cardCountInitVO : cardCountInitList) {
								MemberCardCostCountVO memberCardCostCountVO = new MemberCardCostCountVO();
								memberCardCostCountVO.setCount(cardCountInitVO
										.getCount());
								memberCardCostCountVO
										.setMemberCard(memberCardVO);
								memberCardCostCountVO
										.setProduct(cardCountInitVO
												.getProductVO());
								memberCardCostCountVOList
										.add(memberCardCostCountVO);
							}
							memberCardCostCountService
									.insertVos(memberCardCostCountVOList);
						}
						//ServiceInitVO serviceInitVO = serviceInitService.getVOByMap(paramMap);
						MembercardServiceVO membercardServiceVO = new MembercardServiceVO();
						membercardServiceVO.setMemberCard(memberCardVO);
						// TODO: refactor
						// membercardServiceVO.setServiceId(serviceInitVO.getServiceId());
						membercardServiceService.save(membercardServiceVO);
					}
				} else {// 有申请过
					resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
					resultObject.setMsg("不能重复申请同一张卡");
				}
			} else {
				resultObject.setStatus(ApiConstant.SUCCESS_STATUS);
				resultObject.setMsg("用户不存在");
			}
		} catch (Exception e) {
			resultObject.setStatus(ApiConstant.FALSE_STATUS);
			resultObject.setMsg(ApiConstant.PUBLIC_EXCEPTION);
			e.printStackTrace();
		}

		HttpRequestUtils.printContent(JsonUtils.parseObj2Json(resultObject), response);
		return null;
	}

	public void setCardEntityService(ICardEntityService cardEntityService) {
		this.cardEntityService = cardEntityService;
	}

	public void setRegisterUserService(IRegisterUserService registerUserService) {
		this.registerUserService = registerUserService;
	}

	public void setMemberCardService(IMemberCardService memberCardService) {
		this.memberCardService = memberCardService;
	}

}
